﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace BehaviorCommandExample
{
    public class ScrollViewerWheelScrollBehavior : Behavior<ScrollViewer>
    {
        #region ScrollAmount

        /// <summary> 
        /// Gets or sets the ScrollAmount possible Value of the double object.
        /// </summary> 
        public double ScrollAmount
        {
            get { return (double)GetValue(ScrollAmountProperty); }
            set { SetValue(ScrollAmountProperty, value); }
        }

        /// <summary> 
        /// Identifies the ScrollAmount dependency property.
        /// </summary> 
        public static readonly DependencyProperty ScrollAmountProperty =
                    DependencyProperty.Register(
                          "ScrollAmount",
                          typeof(double),
                          typeof(ScrollViewerWheelScrollBehavior),
                          new PropertyMetadata(1.0, OnScrollAmountPropertyChanged));

        /// <summary>
        /// ScrollAmountProperty property changed handler. 
        /// </summary>
        /// <param name="d">ScrollViewerWheelScrollBehavior that changed its ScrollAmount.</param>
        /// <param name="e">DependencyPropertyChangedEventArgs.</param> 
        private static void OnScrollAmountPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ScrollViewerWheelScrollBehavior _ScrollViewerWheelScrollBehavior = d as ScrollViewerWheelScrollBehavior;
            if (_ScrollViewerWheelScrollBehavior != null)
            {
                //TODO: Handle new value. 
            }
        }
        #endregion ScrollAmount


        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.MouseWheel += new MouseWheelEventHandler(AssociatedObject_MouseWheel);
        }

        void AssociatedObject_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0) // 휠을 올리면 양수
            {
                AssociatedObject.ScrollToVerticalOffset(Math.Max(0, AssociatedObject.VerticalOffset - ScrollAmount));
            }
            else
            {
                AssociatedObject.ScrollToVerticalOffset(Math.Min(AssociatedObject.ScrollableHeight, AssociatedObject.VerticalOffset + ScrollAmount));
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.MouseWheel -= new MouseWheelEventHandler(AssociatedObject_MouseWheel);
        }
    }
}
